package de.schnocklake.android.soap;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.scheme.SocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

import android.util.Log;

public class SoapUtils {
	public static String getBasicAuth(String username, String password) {
		StringBuffer buf = new StringBuffer(username);
		buf.append(':').append(password);
		byte[] raw = buf.toString().getBytes();
		buf.setLength(0);
		buf.append("Basic ");
		org.kobjects.base64.Base64.encode(raw, 0, raw.length, buf);
		return buf.toString();
	}

	
	
	public static Document requestHttpClient(Document document, String url, String username, String password) {
		HttpResponse httpResponse;

		HttpPost request = new HttpPost(url);
		request.addHeader("Authorization", getBasicAuth(username, password));
		request.addHeader("SOAPAction", "http://www.sap.com/RFC_READ_TABLE");

		
// SSL stuff		
		SchemeRegistry schemeRegistry = new SchemeRegistry();

		schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));		
		schemeRegistry.register (new Scheme ("https", new CustomSSLSocketFactory (), 443));
		 
		ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(request.getParams(), schemeRegistry);
//End of  SSL stuff
				
		HttpClient client = new DefaultHttpClient(cm, request.getParams());

		try {
			StringEntity ent = new StringEntity(document.asXML());
			ent.setContentType("text/xml;charset=UTF-8");
			request.setEntity(ent);

			httpResponse = client.execute(request);
			int responseCode = httpResponse.getStatusLine().getStatusCode();
			String message = httpResponse.getStatusLine().getReasonPhrase();

			HttpEntity entity = httpResponse.getEntity();

			if (entity != null) {
				InputStream instream = entity.getContent();
				SAXReader reader = new SAXReader(); // dom4j SAXReader

				Document responseDocument = null;

				Log.i("vor parse", "vor parse");

				responseDocument = reader.read(instream);
				return responseDocument;
			}

		} catch (ClientProtocolException e) {
			client.getConnectionManager().shutdown();
			e.printStackTrace();

		} catch (UnsupportedEncodingException e) {
			client.getConnectionManager().shutdown();
			e.printStackTrace();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}

	
	
	
	public static Document request(Document document, HttpURLConnection connection, String username, String password)
			throws SoapException {
		String request = document.asXML();

		byte[] requestData = request.getBytes();
		try {
			connection.setUseCaches(false);
			connection.setDoOutput(true);
			connection.setDoInput(true);

			if (username != null && password != null) {
				StringBuffer buf = new StringBuffer(username);
				buf.append(':').append(password);
				byte[] raw = buf.toString().getBytes();
				buf.setLength(0);
				buf.append("Basic ");
				org.kobjects.base64.Base64.encode(raw, 0, raw.length, buf);
				connection.setRequestProperty("Authorization", buf.toString());
			}

			connection.setRequestProperty("User-Agent", "Jakarta Commons-HttpClient/3.1");
			connection.setRequestProperty("SOAPAction", "xyungeloesst");
			connection.setRequestProperty("Content-Type", "text/xml");
			connection.setRequestProperty("Connection", "close");
			connection.setRequestProperty("Content-Length", "" + requestData.length);
			connection.setRequestMethod("POST");
			connection.connect();
			OutputStream os = connection.getOutputStream();
			String requestDump = new String(requestData);
			Log.i("request", requestDump);
			os.write(requestData, 0, requestData.length);
			os.flush();
			os.close();

			Log.i("connection.getResponseCode();", "" + connection.getResponseCode());

			InputStream is;
			// connection.connect();
			// is = connection.getInputStream();

			try {
				// connection.connect();
				is = connection.getInputStream();
			} catch (IOException e) {
				Log.i("SAP", "IOException");

				is = connection.getErrorStream();
				if (is == null) {
					connection.disconnect();
					throw (e);
				}
			}

			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			byte[] buf = new byte[256];
			while (true) {
				int rd = is.read(buf, 0, 256);
				if (rd == -1)
					break;
				bos.write(buf, 0, rd);
			}
			bos.flush();
			buf = bos.toByteArray();
			String responseDump = new String(buf);
			Log.i("response", responseDump);
			is.close();
			is = new ByteArrayInputStream(buf);

			SAXReader reader = new SAXReader(); // dom4j SAXReader

			Document responseDocument;

			Log.i("vor parse", "vor parse");
			System.err.println("!!!!!responseDump");
			System.err.println(responseDump);
			responseDocument = reader.read(is);
			Log.i("nach parse", "nach parse");
			connection.disconnect();
			return responseDocument;
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} catch (DocumentException e) {
			e.printStackTrace();
			return null;
		} // dom4j Document
	}

}
